package com.spring.extjs.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.extjs.model.TUser;
import com.spring.extjs.pageModel.UserVO;
import com.spring.extjs.service.IUserService;
import com.spring.extjs.util.JsonResult;

@Controller
@RequestMapping("/user")
public class UserController {

	Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/list")
	public @ResponseBody List<UserVO> userList(int page, int start, int limit) {
		
		return userService.userList();
	}
	
	/**
	 * 方法说明：新建或者保存一个用户的信息<br>
	 * <方法详细>
	 * 当userVO的id为0时，表示是在进行新增操作；
	 * 当userVO的id不为0时，表示是在进行修改操作；
	 * @return JsonResult
	 * @exception
	 * @author chen jie
	 * @since  1.0.0
	 */
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody JsonResult saveOrUpdateUser(UserVO userVO) {
		TUser user = new TUser();
		BeanUtils.copyProperties(userVO, user);
		
		int flag = 0;
		if (user.getId() != null) {
			logger.info("修改一条用户信息：用户名：" + user.getUsername() + ", 修改时间为：" + new Date());
			flag = userService.modifyUser(user);
		} else { 
			logger.info("新增一条用户信息：用户名：" + user.getUsername() + ", 保存时间为：" + new Date());
			flag = userService.insertUser(user);
		}
		if (flag == 1) 
			return new JsonResult(true, "保存成功");
		else 
			return  new JsonResult(false, "保存失败");
	}
	
	@RequestMapping("/delete")
	public @ResponseBody JsonResult deleteUser(String userIds) {
		
		int flag = 0;
		if (!StringUtils.isBlank(userIds)) {
			flag = userService.deleteUsers(userIds);
		}
		
		if (flag > 0) 
			return new JsonResult(true, "删除用户数据成功");
		else 
			return new JsonResult(false, "删除用户数据失败，请查看日志");
	}
}
